[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, isServer, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. import { Comments } from '~/components/Comments';
  17. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. import { PageContentFooter } from '~/components/PageContentFooter';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  22. // import { useIndentSize } from '~/stores/editor';
  23. // import { useRendererSettings } from '~/stores/renderer';
  24. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  25. import { EditorConfig } from '~/interfaces/editor-settings';
  26. import { CustomWindow } from '~/interfaces/global';
  27. import { RendererConfig } from '~/interfaces/services/renderer';
  28. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  29. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  30. import { PageModel, PageDocument } from '~/server/models/page';
  31. import { PageRedirectModel } from '~/server/models/page-redirect';
  32. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  33. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  34. import { useRedirectFrom } from '~/stores/page-redirect';
  35. import {
  36. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  37. } from '~/stores/ui';
  38. import loggerFactory from '~/utils/logger';
  39. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  40. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  41. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  42. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  43. import { BasicLayout } from '../components/Layout/BasicLayout';
  44. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  45. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  46. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  47. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  48. import {
  49. useCurrentUser, useCurrentPagePath,
  50. useIsLatestRevision,
  51. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  52. useIsEnabledStaleNotification, useIsIdenticalPath,
  53. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  54. useHackmdUri,
  55. useIsAclEnabled, useIsUserPage, useIsNotCreatable,
  56. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  57. useIsSlackConfigured, useIsBlinkedHeaderAtBoot, useRendererConfig, useEditingMarkdown,
  58. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  59. } from '../stores/context';
  60. import {
  61. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  62. } from './utils/commons';
  63. // import { useCurrentPageSWR } from '../stores/page';
  64. const logger = loggerFactory('growi:pages:all');
  65. const {
  66. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTrashPage,
  67. } = pagePathUtils;
  68. const { removeHeadingSlash } = pathUtils;
  69. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  70. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  71. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  72. {
  73. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  74. return v?.data != null
  75. && v?.data.toObject != null
  76. && v?.meta != null
  77. && isIPageInfoForEntity(v.meta);
  78. },
  79. serialize: (v) => {
  80. return {
  81. data: superjson.stringify(v.data.toObject()),
  82. meta: superjson.stringify(v.meta),
  83. };
  84. },
  85. deserialize: (v) => {
  86. return {
  87. data: superjson.parse(v.data),
  88. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  89. };
  90. },
  91. },
  92. 'IPageToShowRevisionWithMetaTransformer',
  93. );
  94. const IdenticalPathPage = (): JSX.Element => {
  95. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  96. return <IdenticalPathPage />;
  97. };
  98. const PutbackPageModal = (): JSX.Element => {
  99. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  100. return <PutbackPageModal />;
  101. };
  102. type Props = CommonProps & {
  103. currentUser: IUser,
  104. pageWithMeta: IPageToShowRevisionWithMeta,
  105. // pageUser?: any,
  106. redirectFrom?: string;
  107. // shareLinkId?: string;
  108. isLatestRevision?: boolean
  109. isIdenticalPathPage?: boolean,
  110. isForbidden: boolean,
  111. isNotFound: boolean,
  112. IsNotCreatable: boolean,
  113. // isAbleToDeleteCompletely: boolean,
  114. isSearchServiceConfigured: boolean,
  115. isSearchServiceReachable: boolean,
  116. isSearchScopeChildrenAsDefault: boolean,
  117. isSlackConfigured: boolean,
  118. // isMailerSetup: boolean,
  119. isAclEnabled: boolean,
  120. // hasSlackConfig: boolean,
  121. // drawioUri: string,
  122. hackmdUri: string,
  123. // mathJax: string,
  124. // noCdn: string,
  125. // highlightJsStyle: string,
  126. isAllReplyShown: boolean,
  127. // isContainerFluid: boolean,
  128. editorConfig: EditorConfig,
  129. isEnabledStaleNotification: boolean,
  130. // isEnabledLinebreaks: boolean,
  131. // isEnabledLinebreaksInComments: boolean,
  132. // adminPreferredIndentSize: number,
  133. // isIndentSizeForced: boolean,
  134. disableLinkSharing: boolean,
  135. rendererConfig: RendererConfig,
  136. // UI
  137. userUISettings?: IUserUISettings
  138. // Sidebar
  139. sidebarConfig: ISidebarConfig,
  140. };
  141. const GrowiPage: NextPage<Props> = (props: Props) => {
  142. // const { t } = useTranslation();
  143. const router = useRouter();
  144. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  145. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  146. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  147. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  148. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  149. // register global EventEmitter
  150. if (isClient()) {
  151. (window as CustomWindow).globalEmitter = new EventEmitter();
  152. }
  153. // commons
  154. useEditorConfig(props.editorConfig);
  155. useCsrfToken(props.csrfToken);
  156. // UserUISettings
  157. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  158. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  159. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  160. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  161. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  162. // page
  163. useIsLatestRevision(props.isLatestRevision);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotFound(props.isNotFound);
  167. useIsNotCreatable(props.IsNotCreatable);
  168. useRedirectFrom(props.redirectFrom);
  169. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  170. // useShared();
  171. // useShareLinkId(props.shareLinkId);
  172. useIsSharedUser(false); // this page cann't be routed for '/share'
  173. useIsIdenticalPath(false); // TODO: need to initialize from props
  174. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  175. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  176. useIsBlinkedHeaderAtBoot(false);
  177. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  178. useIsSearchServiceReachable(props.isSearchServiceReachable);
  179. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  180. useIsSlackConfigured(props.isSlackConfigured);
  181. // useIsMailerSetup(props.isMailerSetup);
  182. useIsAclEnabled(props.isAclEnabled);
  183. // useHasSlackConfig(props.hasSlackConfig);
  184. // useDrawioUri(props.drawioUri);
  185. useHackmdUri(props.hackmdUri);
  186. // useMathJax(props.mathJax);
  187. // useNoCdn(props.noCdn);
  188. // useIndentSize(props.adminPreferredIndentSize);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  192. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  193. useIsAllReplyShown(props.isAllReplyShown);
  194. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  195. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  196. // const { data: editorMode } = useEditorMode();
  197. const { pageWithMeta, userUISettings } = props;
  198. let shouldRenderPutbackPageModal = false;
  199. if (pageWithMeta != null) {
  200. shouldRenderPutbackPageModal = _isTrashPage(pageWithMeta.data.path);
  201. }
  202. const pageId = pageWithMeta?.data._id;
  203. useCurrentPageId(pageId);
  204. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  205. useSWRxPageInfo(pageId, undefined, pageWithMeta?.meta); // store initial data
  206. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  207. useIsUserPage(isUserPage(pageWithMeta?.data.path ?? ''));
  208. useIsNotCreatable(props.isForbidden || !isCreatablePage(pageWithMeta?.data.path ?? '')); // TODO: need to include props.isIdentical
  209. useCurrentPagePath(pageWithMeta?.data.path);
  210. useCurrentPathname(props.currentPathname);
  211. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  212. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  213. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  214. // sync grant data
  215. useEffect(() => {
  216. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  217. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  218. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  219. useEffect(() => {
  220. const decodedURI = decodeURI(window.location.pathname);
  221. if (isClient() && decodedURI !== props.currentPathname) {
  222. router.replace(props.currentPathname, undefined, { shallow: true });
  223. }
  224. }, [props.currentPathname, router]);
  225. const classNames: string[] = [];
  226. // switch (editorMode) {
  227. // case EditorMode.Editor:
  228. // classNames.push('on-edit', 'builtin-editor');
  229. // break;
  230. // case EditorMode.HackMD:
  231. // classNames.push('on-edit', 'hackmd');
  232. // break;
  233. // }
  234. // if (page == null) {
  235. // classNames.push('not-found-page');
  236. // }
  237. return (
  238. <>
  239. <Head>
  240. {/*
  241. {renderScriptTagByName('drawio-viewer')}
  242. {renderScriptTagByName('mathjax')}
  243. {renderScriptTagByName('highlight-addons')}
  244. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  245. */}
  246. </Head>
  247. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  248. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  249. <header className="py-0 position-relative">
  250. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  251. </header>
  252. <div className="d-edit-none">
  253. <GrowiSubNavigationSwitcher />
  254. </div>
  255. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  256. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  257. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  258. <div id="content-main" className="content-main grw-container-convertible">
  259. <div className="row">
  260. <div className="col">
  261. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  262. { !props.isIdenticalPathPage && (
  263. <>
  264. <PageAlerts />
  265. { props.isForbidden && <ForbiddenPage /> }
  266. { props.IsNotCreatable && <NotCreatablePage />}
  267. { !props.isForbidden && !props.IsNotCreatable && <DisplaySwitcher />}
  268. {/* <DisplaySwitcher /> */}
  269. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  270. {/* <PageStatusAlert /> */}
  271. </>
  272. ) }
  273. </div>
  274. </div>
  275. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  276. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  277. <div id="revision-toc-content" className="revision-toc-content"></div>
  278. </div>
  279. </div> */}
  280. </div>
  281. </div>
  282. {/* TODO: Check CSS import */}
  283. <footer className="footer d-edit-none">
  284. {/* TODO: Enable page_list.html */}
  285. {/* TODO: Enable isIdenticalPathPage or useIdenticalPath */}
  286. { !props.isIdenticalPathPage && (
  287. <Comments pageId={pageId} isDeleted={isTrashPage(pageWithMeta?.data.path)}/>
  288. )}
  289. {/* TODO: Create UsersHomePageFooter conponent */}
  290. { isUsersHomePage(pageWithMeta?.data.path) && (
  291. <div className="container-lg user-page-footer py-5">
  292. <div className="grw-user-page-list-m d-edit-none">
  293. <h2 id="bookmarks-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  294. <i style={{ fontSize: '1.3em' }} className="fa fa-fw fa-bookmark-o"></i>
  295. Bookmarks
  296. </h2>
  297. <div id="user-bookmark-list" className="page-list">
  298. {/* TODO: No need page-list-container class ? */}
  299. <div className="page-list-container">
  300. {/* <BookmarkList userId={pageContainer.state.creator._id} /> */}
  301. </div>
  302. </div>
  303. </div>
  304. <div className="grw-user-page-list-m mt-5 d-edit-none">
  305. <h2 id="recently-created-list" className="grw-user-page-header border-bottom pb-2 mb-3">
  306. <i id="recent-created-icon" className="mr-1">
  307. {/* <RecentlyCreatedIcon /> */}
  308. </i>
  309. Recently Created
  310. </h2>
  311. <div id="user-created-list" className="page-list">
  312. {/* TODO: No need page-list-container class ? */}
  313. <div className="page-list-container">
  314. {/* <RecentCreated userId={pageContainer.state.creator._id} /> */}
  315. </div>
  316. </div>
  317. </div>
  318. </div>
  319. )}
  320. <PageContentFooter />
  321. </footer>
  322. <UnsavedAlertDialog />
  323. <DescendantsPageListModal />
  324. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  325. </BasicLayout>
  326. </>
  327. );
  328. };
  329. function getPageIdFromPathname(currentPathname: string): string | null {
  330. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  331. }
  332. class MultiplePagesHitsError extends ExtensibleCustomError {
  333. pagePath: string;
  334. constructor(pagePath: string) {
  335. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  336. this.pagePath = pagePath;
  337. }
  338. }
  339. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  340. const req: CrowiRequest = context.req as CrowiRequest;
  341. const { crowi } = req;
  342. const { revisionId } = req.query;
  343. const Page = crowi.model('Page') as PageModel;
  344. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  345. const { pageService } = crowi;
  346. let currentPathname = props.currentPathname;
  347. const pageId = getPageIdFromPathname(currentPathname);
  348. const isPermalink = _isPermalink(currentPathname);
  349. const { user } = req;
  350. if (!isPermalink) {
  351. // check redirects
  352. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  353. if (chains != null) {
  354. // overwrite currentPathname
  355. currentPathname = chains.end.toPath;
  356. props.currentPathname = currentPathname;
  357. // set redirectFrom
  358. props.redirectFrom = chains.start.fromPath;
  359. }
  360. // check whether the specified page path hits to multiple pages
  361. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  362. if (count > 1) {
  363. throw new MultiplePagesHitsError(currentPathname);
  364. }
  365. }
  366. const pageWithMeta: IPageToShowRevisionWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  367. const page = pageWithMeta?.data as unknown as PageDocument;
  368. // populate & check if the revision is latest
  369. if (page != null) {
  370. page.initLatestRevisionField(revisionId);
  371. await page.populateDataToShowRevision();
  372. props.isLatestRevision = page.isLatestRevision();
  373. }
  374. props.pageWithMeta = pageWithMeta;
  375. }
  376. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  377. const req = context.req as CrowiRequest<IUserHasId & any>;
  378. const { user } = req;
  379. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  380. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  381. if (userUISettings != null) {
  382. props.userUISettings = userUISettings.toObject();
  383. }
  384. }
  385. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  386. const req: CrowiRequest = context.req as CrowiRequest;
  387. const { crowi } = req;
  388. const Page = crowi.model('Page') as PageModel;
  389. const { currentPathname } = props;
  390. const pageId = getPageIdFromPathname(currentPathname);
  391. const isPermalink = _isPermalink(currentPathname);
  392. const page = props.pageWithMeta?.data;
  393. if (props.isIdenticalPathPage) {
  394. // TBD
  395. }
  396. else if (page == null) {
  397. props.isNotFound = true;
  398. props.IsNotCreatable = !isCreatablePage(currentPathname);
  399. // check the page is forbidden or just does not exist.
  400. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  401. props.isForbidden = count > 0;
  402. }
  403. else {
  404. props.isNotFound = page.isEmpty;
  405. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  406. if (isPermalink && page.isEmpty) {
  407. props.currentPathname = page.path;
  408. }
  409. // /path/to/page ==> /62a88db47fed8b2d94f30000
  410. if (!isPermalink && !page.isEmpty) {
  411. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  412. if (!isToppage) {
  413. props.currentPathname = `/${page._id}`;
  414. }
  415. }
  416. }
  417. }
  418. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  419. // const req: CrowiRequest = context.req as CrowiRequest;
  420. // const { crowi } = req;
  421. // const UserModel = crowi.model('User');
  422. // if (isUserPage(props.currentPagePath)) {
  423. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  424. // if (user != null) {
  425. // props.pageUser = JSON.stringify(user.toObject());
  426. // }
  427. // }
  428. // }
  429. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  430. const req: CrowiRequest = context.req as CrowiRequest;
  431. const { crowi } = req;
  432. const {
  433. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  434. } = crowi;
  435. props.isSearchServiceConfigured = searchService.isConfigured;
  436. props.isSearchServiceReachable = searchService.isReachable;
  437. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  438. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  439. // props.isMailerSetup = mailService.isMailerSetup;
  440. props.isAclEnabled = aclService.isAclEnabled();
  441. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  442. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  443. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  444. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  445. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  446. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  447. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  448. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  449. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  450. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  451. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  452. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  453. props.editorConfig = {
  454. upload: {
  455. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  456. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  457. },
  458. };
  459. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  460. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  461. props.rendererConfig = {
  462. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  463. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  464. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  465. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  466. plantumlUri: process.env.PLANTUML_URI ?? null,
  467. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  468. // XSS Options
  469. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  470. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  471. tagWhiteList: crowi.xssService.getTagWhiteList(),
  472. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  473. };
  474. props.sidebarConfig = {
  475. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  476. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  477. };
  478. }
  479. /**
  480. * for Server Side Translations
  481. * @param context
  482. * @param props
  483. * @param namespacesRequired
  484. */
  485. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  486. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  487. props._nextI18Next = nextI18NextConfig._nextI18Next;
  488. }
  489. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  490. const req = context.req as CrowiRequest<IUserHasId & any>;
  491. const { user } = req;
  492. const result = await getServerSideCommonProps(context);
  493. // check for presence
  494. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  495. if (!('props' in result)) {
  496. throw new Error('invalid getSSP result');
  497. }
  498. const props: Props = result.props as Props;
  499. if (user != null) {
  500. props.currentUser = user.toObject();
  501. }
  502. try {
  503. await injectPageData(context, props);
  504. }
  505. catch (err) {
  506. if (err instanceof MultiplePagesHitsError) {
  507. props.isIdenticalPathPage = true;
  508. }
  509. else {
  510. throw err;
  511. }
  512. }
  513. await injectUserUISettings(context, props);
  514. await injectRoutingInformation(context, props);
  515. injectServerConfigurations(context, props);
  516. await injectNextI18NextConfigurations(context, props, ['translation']);
  517. return {
  518. props,
  519. };
  520. };
  521. export default GrowiPage;